package com.beyondsoft.sabg.edu.service.dataanalysis.impl;

import com.aliyun.dataanalysisgbi20240823.models.CreateDatasourceAuthorizationRequest;
import com.aliyun.dataanalysisgbi20240823.models.CreateDatasourceAuthorizationResponse;
import com.aliyun.dataanalysisgbi20240823.models.SyncRemoteTablesRequest;
import com.aliyun.dataanalysisgbi20240823.models.SyncRemoteTablesResponse;
import com.aliyun.dataanalysisgbi20240823.models.ListSelectedTablesRequest;
import com.aliyun.dataanalysisgbi20240823.models.ListSelectedTablesResponse;
import com.aliyun.dataanalysisgbi20240823.models.ResyncTableRequest;
import com.aliyun.dataanalysisgbi20240823.models.ResyncTableResponse;
import com.aliyun.dataanalysisgbi20240823.models.ListColumnRequest;
import com.aliyun.dataanalysisgbi20240823.models.ListColumnResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.beyondsoft.sabg.edu.config.AnalysisConfig;
import com.beyondsoft.sabg.edu.model.dto.DataSourceConfigDto;
import com.beyondsoft.sabg.edu.service.dataanalysis.DataSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据源服务实现类
 */
@Service
@Slf4j
public class DataSourceServiceImpl implements DataSourceService {

    @Autowired
    private com.aliyun.dataanalysisgbi20240823.Client analysisClient;

    @Autowired
    private AnalysisConfig analysisConfig;

    @Override
    public String createDatasourceAuthorization(DataSourceConfigDto config) throws Exception {
        log.info("创建数据源授权，URL：{}", config.getUrl());

        try {
            CreateDatasourceAuthorizationRequest request = new CreateDatasourceAuthorizationRequest()
                    .setWorkspaceId(analysisConfig.getWorkspaceId())
                    .setType(config.getType())
                    .setUrl(config.getUrl())
                    .setUserName(config.getUserName())
                    .setPassword(config.getPassword());

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();
            
            CreateDatasourceAuthorizationResponse response = analysisClient
                    .createDatasourceAuthorizationWithOptions(request, headers, runtime);

            // 添加调试日志
            log.info("完整响应: {}", response);
            log.info("响应状态码: {}", response.getStatusCode());
            log.info("响应Body: {}", response.getBody());
            
            if (response.getBody() != null) {
                log.info("数据源授权创建完成，请求ID：{}", response.getBody().getRequestId());
                log.info("Success: {}", response.getBody().getSuccess());
                
                if (response.getBody().getSuccess() != null && response.getBody().getSuccess()) {
                    return "数据源授权创建成功，请求ID：" + response.getBody().getRequestId();
                } else {
                    throw new RuntimeException("创建数据源授权失败：" + response.getBody().getErrorMsg());
                }
            } else {
                throw new RuntimeException("创建数据源授权失败：响应Body为空");
            }

        } catch (Exception e) {
            log.error("创建数据源授权失败", e);
            throw new RuntimeException("创建数据源授权失败：" + e.getMessage(), e);
        }
    }

    @Override
    public String syncRemoteTables(List<String> tableNames) throws Exception {
        log.info("同步远程数据表，表数量：{}", tableNames.size());

        try {
            SyncRemoteTablesRequest request = new SyncRemoteTablesRequest()
                    .setTableNames(tableNames)
                    .setWorkspaceId(analysisConfig.getWorkspaceId());

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();

            SyncRemoteTablesResponse response = analysisClient
                    .syncRemoteTablesWithOptions(request, headers, runtime);

            
            if (response.getBody() != null) {
                    return "数据表同步成功:" + response.getBody().getData();

            } else {
                throw new RuntimeException("同步数据表失败：响应Body为空");
            }

        } catch (Exception e) {
            log.error("同步数据表失败", e);
            throw new RuntimeException("同步数据表失败：" + e.getMessage(), e);
        }
    }

    @Override
    public Object listSelectedTables() throws Exception {
        log.info("获取数据表合集");
        
        try {
            ListSelectedTablesRequest request = new ListSelectedTablesRequest()
                    .setWorkspaceId(analysisConfig.getWorkspaceId());

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();

            ListSelectedTablesResponse response = analysisClient
                    .listSelectedTablesWithOptions(request, headers, runtime);

            if (response.getBody() != null) {
                return response.getBody().getData();
            } else {
                throw new RuntimeException("获取数据表合集失败：响应Body为空");
            }

        } catch (Exception e) {
            log.error("获取数据表合集失败", e);
            throw new RuntimeException("获取数据表合集失败：" + e.getMessage(), e);
        }
    }

    @Override
    public Object resyncTable(String tableIdKey) throws Exception {
        log.info("刷新数据表，表ID：{}", tableIdKey);
        
        try {
            ResyncTableRequest request = new ResyncTableRequest()
                    .setWorkspaceId(analysisConfig.getWorkspaceId())
                    .setTableIdKey(tableIdKey);

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();

            ResyncTableResponse response = analysisClient
                    .resyncTableWithOptions(request, headers, runtime);

            if (response.getBody() != null) {
                return response.getBody().getData();
            } else {
                throw new RuntimeException("刷新数据表失败：响应Body为空");
            }

        } catch (Exception e) {
            log.error("刷新数据表失败", e);
            throw new RuntimeException("刷新数据表失败：" + e.getMessage(), e);
        }
    }

    @Override
    public Object listColumns(String tableIdKey) throws Exception {
        log.info("获取数据表列信息，表ID：{}", tableIdKey);
        
        try {
            ListColumnRequest request = new ListColumnRequest()
                    .setTableIdKey(tableIdKey)
                    .setWorkspaceId(analysisConfig.getWorkspaceId());

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();

            ListColumnResponse response = analysisClient
                    .listColumnWithOptions(request, headers, runtime);

            if (response.getBody() != null) {
                return response.getBody().getData();
            } else {
                throw new RuntimeException("获取数据表列信息失败：响应Body为空");
            }

        } catch (Exception e) {
            log.error("获取数据表列信息失败", e);
            throw new RuntimeException("获取数据表列信息失败：" + e.getMessage(), e);
        }
    }
}